package cn.uncode.rpc.transport.netty.client;

import java.net.SocketAddress;
import java.nio.channels.Channel;
import java.util.concurrent.ConcurrentHashMap;

import cn.uncode.rpc.core.Response;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

public class NettyClientHandler extends SimpleChannelInboundHandler<Response> {
	
	private ConcurrentHashMap<String, MessageCallBack> mapCallBack = new ConcurrentHashMap<String, MessageCallBack>();
	
	
	volatile private io.netty.channel.Channel channel;
    private SocketAddress remoteAddr;
	
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
        super.channelActive(ctx);
        this.remoteAddr = ctx.channel().remoteAddress();
    }
	
	

    public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
        super.channelRegistered(ctx);
        this.channel = ctx.channel();
    }

	@Override
	protected void channelRead0(ChannelHandlerContext ctx, Response response) throws Exception {
        Long messageId = response.getRequestId();
        MessageCallBack callBack = mapCallBack.get(messageId);
        if (callBack != null) {
            mapCallBack.remove(messageId);
            callBack.over(response);
        }
	}
	
	
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }
    
    public void close() {
        channel.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
    }

}
